﻿using System;
using System.IO;
using System.Reflection;
using System.Text;
using EnvDTE;
using SpecFlowTfsLinker.Printer;
using SpecFlowTfsLinker.SpecFlowFile;

namespace SpecFlowTfsLinker.VisualStudioHelper
{
    public static class SpecFlowFileGenerator
    {
        public static void GenererFichier(ISpecFlowFile specFlowFile, ISpecFlowPrinter printer, ProjectItem vsFolder)
        {
            var assemblyDirectory = RetrieveAssemblyDirectory();
            var specFlowFilePath = Path.Combine(assemblyDirectory, specFlowFile.FileName);

            File.WriteAllText(specFlowFilePath, printer.Print(), Encoding.UTF8);
            vsFolder.ProjectItems.AddFromTemplate(specFlowFilePath, specFlowFile.FileName);
        }

        private static string RetrieveAssemblyDirectory()
        {
            var codeBase = Assembly.GetExecutingAssembly().CodeBase;
            var uri = new UriBuilder(codeBase);
            var path = Uri.UnescapeDataString(uri.Path);
            return Path.GetDirectoryName(path);
        }
    }
}